package com.khmt2k3.xuantung.vnexpressnews;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;

public class ListNewsActivity extends ListActivity
{
	private String linkRSS = ""; //link RSS de lay tin
	int first = 0; //tin dau tien
	int itemsPerScroll = 1; //so tin lay' them khi cuon. listview
	int end = 5; //tin cuoi'
	ParserRSS parserRSS;
	AdapterNews adapter;
	boolean check = false;

	

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		Log.d("start","2");
		
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) 
		{
			this.linkRSS = bundle.getString("linkRSS");
		}		
	
		//load news tu internet ve
		parserRSS = new ParserRSS();
		parserRSS.setLinkRSS(linkRSS);	
		parserRSS.loadDocument();
		//------------------

		adapter = new AdapterNews(parserRSS.listNews, getApplicationContext());
		setListAdapter(adapter);

		this.getListView().setOnScrollListener(new OnScrollListener() 
		{

			//@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) 
			{

			}
			
			//Khi nao load toi' news cuoi' cung ma van muon doc tin tiep thi se load them news, so tin duoc load ten = itemsperscroll

			//@Override
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount)
			{
				int count = firstVisibleItem + visibleItemCount;
				if (count == totalItemCount) 
				{	Log.d("more","run");
					
					runOnUiThread(loadMoreItems);					
				}

			}
		});

	}

	private Runnable loadMoreItems = new Runnable() 
	{

		//@Override
		public void run() 
		{
				parserRSS.loadNews(first, end);
				first = end;
				end += itemsPerScroll;
	
				runOnUiThread(refesh);
			
		}
	};

	private Runnable refesh = new Runnable() 
	{

		//@Override
		public void run() 
		{
			adapter.notifyDataSetChanged();			
		}
	};

	
	//chuyen mau su title cua tin duoc doc.
	protected void onPause() 
	{
		super.onPause();
		adapter.notifyDataSetChanged();
	};
	
}
